<template>
  <div class="statistics-container">
    <h2>数据统计</h2>
    
    <!-- 用户标签列表，只有管理员可见 -->
    <div v-if="isAdmin" class="user-tabs">
      <button 
        class="user-tab" 
        :class="{ active: selectedUser === 'all' }"
        @click="selectUser('all')"
      >
        全部用户
      </button>
      <button 
        v-for="stat in userStats" 
        :key="stat.username"
        class="user-tab"
        :class="{ active: selectedUser === stat.username }"
        @click="selectUser(stat.username)"
      >
        {{ stat.username }} ({{ stat.count }})
      </button>
    </div>

    <!-- 月份选择器 -->
    <div class="month-selector">
      <button 
        class="month-tab"
        :class="{ active: selectedMonth === 'all' }"
        @click="selectedMonth = 'all'"
      >
        全部时间
      </button>
      <button 
        v-for="month in availableMonths" 
        :key="month"
        class="month-tab"
        :class="{ active: selectedMonth === month }"
        @click="selectedMonth = month"
      >
        {{ formatMonth(month) }}
      </button>
    </div>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <div class="stat-card">
        <h4>任务总数</h4>
        <div class="stat-value">{{ filteredStats.totalTasks }}</div>
      </div>
      <div class="stat-card">
        <h4>本月任务数</h4>
        <div class="stat-value">{{ filteredStats.monthlyTasks }}</div>
      </div>
      <div class="stat-card">
        <h4>任务等级分布</h4>
        <div class="stat-value">
          <div v-for="(count, priority) in filteredStats.priorityStats" :key="priority">
            {{ priority }}: {{ count }}
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 任务性质分布 -->
      <div class="chart-section">
        <h3>任务性质分布</h3>
        <div class="chart-container" ref="natureChartContainer"></div>
      </div>
      
      <!-- 任务来源分布 -->
      <div class="chart-section">
        <h3>任务来源分布</h3>
        <div class="chart-container" ref="sourceChartContainer"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import config from '../config'
import * as echarts from 'echarts'

const router = useRouter()
const userStats = ref([])
const selectedUser = ref('all')
const selectedMonth = ref('all')
const natureChartContainer = ref(null)
const sourceChartContainer = ref(null)
let natureChart = null
let sourceChart = null
const currentUserStats = ref({
  totalTasks: 0,
  monthlyTasks: 0,
  priorityStats: {},
  natureStats: {},
  sourceStats: {}
})

const isAdmin = ref(false)
const currentUser = ref(null)

const formatMonth = (month) => {
  const [year, monthNum] = month.split('-')
  return `${year}年${monthNum}月`
}

const availableMonths = computed(() => {
  const months = new Set()
  const tasks = currentUserStats.value?.tasks || []
  const filteredTasks = tasks.filter(task => {
    if (selectedUser.value === 'all') {
      return true
    }
    return task.username === selectedUser.value
  })

  filteredTasks.forEach(task => {
    if (task.date && task.date !== '/') {
      const [year, month] = task.date.split('-')
      if (year && month) {
        months.add(`${year}-${month}`)
      }
    }
  })
  return Array.from(months).sort().reverse() // 最新的月份在前
})

const filteredStats = computed(() => {
  if (selectedMonth.value === 'all') {
    const stats = {
      totalTasks: 0,
      monthlyTasks: 0,
      priorityStats: {},
      natureStats: {},
      sourceStats: {}
    }
    
    const tasks = currentUserStats.value?.tasks || []
    const filteredTasks = tasks.filter(task => 
      selectedUser.value === 'all' || task.username === selectedUser.value
    )
    
    filteredTasks.forEach(task => {
      stats.totalTasks++
      stats.monthlyTasks++
      
      const nature = task.task_nature || '未设置'
      stats.natureStats[nature] = (stats.natureStats[nature] || 0) + 1
      
      const source = task.task_source || '未设置'
      stats.sourceStats[source] = (stats.sourceStats[source] || 0) + 1
      
      const priority = task.task_priority || '未设置'
      stats.priorityStats[priority] = (stats.priorityStats[priority] || 0) + 1
    })
    
    return stats
  }

  const stats = {
    totalTasks: 0,
    monthlyTasks: 0,
    priorityStats: {},
    natureStats: {},
    sourceStats: {}
  }

  const tasks = currentUserStats.value?.tasks || []
  const filteredTasks = tasks.filter(task => {
    if (!task.date || task.date === '/') return false
    return task.date.startsWith(selectedMonth.value) && 
           (selectedUser.value === 'all' || task.username === selectedUser.value)
  })

  filteredTasks.forEach(task => {
    stats.totalTasks++
    stats.monthlyTasks++
    
    const nature = task.task_nature || '未设置'
    stats.natureStats[nature] = (stats.natureStats[nature] || 0) + 1
    
    const source = task.task_source || '未设置'
    stats.sourceStats[source] = (stats.sourceStats[source] || 0) + 1
    
    const priority = task.task_priority || '未设置'
    stats.priorityStats[priority] = (stats.priorityStats[priority] || 0) + 1
  })

  return stats
})

const selectUser = async (username) => {
  selectedUser.value = username
  selectedMonth.value = 'all' // 重置为全部时间
  await fetchUserStats(username)
}

const fetchStatistics = async () => {
  try {
    const user = JSON.parse(localStorage.getItem('user'))
    if (!user) {
      router.push('/login')
      return
    }

    currentUser.value = user
    isAdmin.value = user.role >= 10

    const response = await request.get(config.endpoints.statistics)
    userStats.value = response.data.userStats
    await selectUser('all')
  } catch (error) {
    console.error('获取统计数据失败:', error)
    if (error.response?.status === 401) {
      router.push('/login')
    }
  }
}

const fetchUserStats = async (username) => {
  try {
    const user = JSON.parse(localStorage.getItem('user'))
    // 如果是普通用户，强制使用自己的用户名
    if (user.role < 10) {
      username = user.username
    }

    const response = await request.get(config.endpoints.userStatistics, {
      params: { username: username === 'all' ? '' : username }
    })

    // 获取任务列表数据
    const tasksResponse = await request.get(config.endpoints.tasks, {
      params: { 
        username: username,
        pageSize: 1000
      }
    })

    // 合并数据
    currentUserStats.value = {
      ...response.data,
      tasks: tasksResponse.data.data
    }

    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  }
}

const updateCharts = () => {
  // 更新任务性质饼图
  if (!natureChart) {
    natureChart = echarts.init(natureChartContainer.value)
  }
  const natureOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '70%',
      data: Object.entries(filteredStats.value.natureStats).map(([name, value]) => ({
        name,
        value
      }))
    }]
  }
  natureChart.setOption(natureOption)

  // 更新任务来源饼图
  if (!sourceChart) {
    sourceChart = echarts.init(sourceChartContainer.value)
  }
  const sourceOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '70%',
      data: Object.entries(filteredStats.value.sourceStats).map(([name, value]) => ({
        name,
        value
      }))
    }]
  }
  sourceChart.setOption(sourceOption)
}

// 监听月份变化，更新图表
watch([selectedMonth], () => {
  updateCharts()
})

onMounted(() => {
  fetchStatistics()
  
  window.addEventListener('resize', () => {
    natureChart?.resize()
    sourceChart?.resize()
  })
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.user-tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.user-tab {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.user-tab.active {
  background: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-card h4 {
  margin: 0 0 10px 0;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.month-selector {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.month-tab {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 16px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.month-tab.active {
  background: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.month-tab:hover {
  background: #e8f5e9;
  border-color: #4CAF50;
}

.month-tab.active:hover {
  background: #43a047;
}
</style> 